import json
from datetime import datetime, timedelta

from django.core.paginator import Paginator
from django.db.models import Q
from django.shortcuts import render, HttpResponse
from jwt.exceptions import ExpiredSignatureError
from utils import responsedata

from user.models import User
from utils.customerutils import CustomerUtils
from utils.responsestatus import ResponseStatus
from django_vue_back import settings
from django.db import IntegrityError


# Create your views here.
# 用户认证
def user_login(request):
    # post  认证参数json格式的数据
    user_form = CustomerUtils.get_request_data(request)
    # 密码加密
    user_form['password'] = CustomerUtils.md5(user_form['password'])
    # user_form {username:'admin',password:'111111'}
    db_user = User.objects.filter(**user_form).first()
    if db_user is None:
        # 用户名或密码错误
        response = {
            'code': ResponseStatus.BUSINESS_ERROR,
            'message': '用户名或密码错误'
        }
        return CustomerUtils.response_json(response)

    # 判定用户状态  active  0  禁用
    if db_user.active == 0:
        response = {
            'code': ResponseStatus.BUSINESS_ERROR,
            'message': '账号被禁用,请联系管理员!!!'
        }
        return CustomerUtils.response_json(response)

    # 用户认证通过  生成token
    payload = {
        'id': db_user.id,
        'username': db_user.username,
        'exp': datetime.utcnow() + timedelta(days=1)
    }

    token = CustomerUtils.create_token(payload, settings.SECRET)
    response = {
        'code': ResponseStatus.BUSINESS_SUCCESS,
        'message': '认证通过',
        'data': {
            'token': token
        }
    }
    return CustomerUtils.response_json(response)


# 获取用户信息
def user_info(request):
    if request.method == 'GET':
        token = request.GET.get('token')
        # 反向解析token
        try:
            user_token_dict = CustomerUtils.verify_token(token, settings.SECRET)
            user_id = user_token_dict['id']
            db_user = User.objects.filter(id=user_id).first()
            response = {
                'code': ResponseStatus.BUSINESS_SUCCESS,
                'data': {
                    'name': db_user.username,
                    'avatar': db_user.avatar,
                    'roles': [db_user.role.role_en]
                }
            }
            return CustomerUtils.response_json(response)
        except ExpiredSignatureError as e:
            response = {
                'code': ResponseStatus.TOKEN_EXPIRED,
                'message': 'token已失效,请重新认证'
            }
            return CustomerUtils.response_json(response)
        except Exception as e:
            response = {
                'code': ResponseStatus.ILLEGAL_TOKEN,
                'message': 'token异常,请重新认证'
            }
            return CustomerUtils.response_json(response)


# 用户分页数据
def user_page(request):
    if request.method == 'POST':
        # {page:1,size:5，username,email,active}
        form_data = CustomerUtils.get_request_data(request)
        condition = Q()
        # 动态条件
        if form_data.get('username').strip():
            condition &= Q(username__icontains=form_data['username'])
        if form_data.get('email').strip():
            condition &= Q(email__icontains=form_data['email'])
        # active  0  1
        if form_data.get('active') != '':
            condition &= Q(active=form_data['active'])
        # 分页处理  total  tableData
        user_list = User.objects.filter(condition).order_by('-id')
        # 获取分页对象
        paginator = Paginator(user_list, form_data.get('size', 5))
        # 获取数据总条数
        total = paginator.count
        # 当前页对象
        current_page = paginator.page(form_data.get('page', 1))
        # 当前页数据   [{},{},{}]
        table_data = current_page.object_list
        users = []
        for user in table_data:
            users.append({
                'id': user.id,
                'username': user.username,
                'age': user.age,
                'email': user.email,
                'active': user.active,
                'create_time': user.create_time.strftime('%Y-%m-%d'),
                'role_name': user.role.role_name,
                'dept_name': user.dept.dept_name
            })

        response = {
            'code': ResponseStatus.BUSINESS_SUCCESS,
            'data': {
                'total': total,
                'tableData': users
            }
        }

        return CustomerUtils.response_json(response)


def user_state(request):
    if request.method == 'POST':
        form_data = CustomerUtils.get_request_data(request)
        User.objects.filter(id=form_data.get('id')).update(active=form_data.get('state'))
        return CustomerUtils.response_json(responsedata.BUSINESS_SUCCESS_DATA)


def user_reset_pwd(request, id):
    default_pwd = '111111'
    User.objects.filter(id=id).update(password=CustomerUtils.md5(default_pwd))
    return CustomerUtils.response_json(responsedata.BUSINESS_SUCCESS_DATA)


def user_one(request, id):
    user_one = User.objects.filter(id=id).first()
    response = {
        'code': ResponseStatus.BUSINESS_SUCCESS,
        'data': {
            'user': {
                'id': user_one.id,
                'username': user_one.username,
                'age': user_one.age,
                'email': user_one.email,
                'active': user_one.active,
                'role_id': user_one.role_id,
                'dept_id': user_one.dept_id
            }
        }
    }
    return CustomerUtils.response_json(response)


def user_insert_edit(request):
    if request.method == 'POST':
        form_data = CustomerUtils.get_request_data(request)
        user_id = form_data.get('id')
        try:
            if user_id is not None:
                # 更新
                User.objects.filter(id=user_id).update(**form_data)
            else:
                # 添加用户信息   设置默认密码   111111
                form_data['password'] = CustomerUtils.md5('111111')
                User(**form_data).save()
        except IntegrityError as e:
            response = responsedata.BUSINESS_ERROR_DATA
            response['message'] = str(e)
            return CustomerUtils.response_json(response)
        else:
            return CustomerUtils.response_json(responsedata.BUSINESS_SUCCESS_DATA)


def user_batch_remove(request):
    if request.method == 'POST':
        form_data = CustomerUtils.get_request_data(request)
        User.objects.filter(id__in=form_data.get('ids')).delete()
        return CustomerUtils.response_json(responsedata.BUSINESS_SUCCESS_DATA)
